package com.bolehui.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bolehui.base.result.Result;
import com.bolehui.base.utils.StringUtils;
import com.bolehui.domain.dto.AreaDTO;
import com.bolehui.domain.po.AreaPO;
import com.bolehui.mapper.AreaMapper;
import com.bolehui.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author chendongjie     email:chendongjie@gz.iscas.ac.cn
 * @version 1.0
 * @ClassName AreaServiceImpl
 * @Description
 * @createTime 2024/12/18 10:22
 * Copyright (C) 2021-2022 CASEEDER, All Rights Reserved.
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 */
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, AreaPO> implements AreaService {

    @Autowired
    private AreaMapper areaMapper;

    public Result getAreaList() {
        List<AreaPO> areaPOS = areaMapper.selectProvincesAndDistricts();

        Map<String, List<AreaPO>> groupedByProvince = areaPOS.stream()
                .collect(Collectors.groupingBy(AreaPO::getProvinceName));
        ArrayList<AreaDTO> areaDTOS = new ArrayList<>();
        for (Map.Entry<String, List<AreaPO>> provinceName : groupedByProvince.entrySet()) {
            AreaDTO areaDTO = new AreaDTO();
            areaDTO.setLabel(provinceName.getKey());

            if (provinceName.getValue().size() == 1 && provinceName.getKey().equals(provinceName.getValue().get(0).getLabel())) {
                areaDTO.setValue(provinceName.getValue().get(0).getValue());
            }
            else {
                areaDTO.setValue(provinceName.getValue().get(0).getParentCode());
                areaDTO.setChildren(provinceName.getValue());
            }
            areaDTOS.add(areaDTO);
        }
        return Result.success(areaDTOS);
    }

    @Override
    public Result getAreaByCode(String areaCode) {
        String label = areaMapper.getAreaByCode(areaCode);
        if(StringUtils.isEmpty(label)){
            return Result.fail("");
        }
        return Result.success(label);
    }

    @Override
    public Result getCodeByAreaName(String areaName) {
        AreaPO areaPO = areaMapper.selectOne(new QueryWrapper<AreaPO>()
                .eq("all_area_name", areaName)
                .isNotNull("parent_id"));

        return Result.success(areaPO);
    }
}
